#include "botthread.h"

BotThread::BotThread(int ID, QObject *parent) :
    QThread(parent)
{
    this->socketDescriptor = ID;
}

void BotThread::run()
{
    //Thread starts here
    qDebug() << socketDescriptor << " Starting Thread";
    socket = new QTcpSocket();

    if(!socket->setSocketDescriptor(this->socketDescriptor))
    {
        emit error(socket->error());
        return;
    }

    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()), Qt::DirectConnection);
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);

    qDebug() << socketDescriptor << " Client Connected";
    emit AddSocket(socketDescriptor);
    exec(); //Stay alive until we close
}

void BotThread::readyRead()
{
    QByteArray Data = socket->readAll();
    QByteArray ackMessage;
    ackMessage.insert(0, EnMsg_ACK);

    qDebug() << "AckMessage: " << " Data out" << ackMessage.data();

    emit MsgChange(QString(Data) + ":" + QString::number(socketDescriptor)); //Append SocketDescriptor
    qDebug() << "***************Signal Emitted!!!!!****************" << QString(Data);
    socket->write(ackMessage.data());
}

void BotThread::disconnected()
{
    qDebug() << socketDescriptor << " Dissconnected";
    emit DeleteSocket(socketDescriptor);
    socket->deleteLater();
    exit(0);
}
